﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace ChinaSoft.Common
{
    public class UpFile
    {
        public UpFile() { }

        #region 是否允许该扩展名上传IsAllowedExtension
        ///<summary> 
        ///是否允许该扩展名上传 
        ///</summary> 
        ///<paramname = "hifile">HtmlInputFile控件</param> 
        ///<returns>允许则返回true,否则返回false</returns> 
        public bool IsAllowedExtension(HtmlInputFile hifile)
        {
            string strOldFilePath = "";
            string strExtension = "";

            //允许上传的扩展名，可以改成从配置文件中读出 
            string[] arrExtension = { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };

            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名 
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //判断该扩展名是否合法 
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.Equals(arrExtension[i]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        #endregion

        #region 判断上传文件大小是否超过最大值IsAllowedLength
        /// <summary> 
        /// 判断上传文件大小是否超过最大值 
        /// </summary> 
        /// <param name="hifile">HtmlInputFile控件</param> 
        /// <returns>超过最大值返回false,否则返回true.</returns> 
        public bool IsAllowedLength(HtmlInputFile hifile)
        {
            //允许上传文件大小的最大值,可以保存在xml文件中,单位为KB 
            int i = 20;
            //如果上传文件的大小超过最大值,返回flase,否则返回true. 
            if (hifile.PostedFile.ContentLength > i * 1024)
            {
                return false;
            }
            return true;
        }
        #endregion


        #region 获取一个不重复的文件名GetUniqueString
        /// <summary> 
        /// 获取一个不重复的文件名 
        /// </summary> 
        /// <returns></returns> 
        public string GetUniqueString()
        {
            //得到的文件名形如：20050922101010 
            return DateTime.Now.ToString("yyyyMMddhhmmss");
        }
        /// <summary>
        /// 获取一个不重复的文件名
        /// </summary>
        /// <param name="State">状态</param>
        /// <returns></returns>
        public string GetUniqueString(string State)
        {
            return Guid.NewGuid().ToString();
        }
        #endregion

        #region 删除指定文件DeleteFile
        /// <summary> 
        /// 删除指定文件 
        /// </summary> 
        /// <param name="strAbsolutePath">文件绝对路径</param> 
        /// <param name="strFileName">文件名</param> 
        public void DeleteFile(string strAbsolutePath, string strFileName)
        {
            //判断路径最后有没有\符号，没有则自动加上 
            if (strAbsolutePath.LastIndexOf("\\") == strAbsolutePath.Length)
            {
                //判断要删除的文件是否存在 
                if (File.Exists(strAbsolutePath + strFileName))
                {
                    try
                    {
                        //删除文件 
                        File.Delete(strAbsolutePath + strFileName);
                    }
                    catch (Exception)
                    {

                    }
                }
            }
            else
            {
                if (File.Exists(strAbsolutePath + "\\" + strFileName))
                {
                    try
                    {
                        //删除文件 
                        File.Delete(strAbsolutePath + "\\" + strFileName);
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }
        #endregion


        #region 上传文件并返回文件名 SaveFile
        /// <summary> 
        /// 上传文件并返回文件名 
        /// </summary> 
        /// <param name="hifile">HtmlInputFile控件</param> 
        /// <param name="strAbsolutePath">绝对路径.如:Server.MapPath(@"Image/upload")与Server.MapPath(@"Image/upload/")均可,用\符号亦可</param> 
        /// <returns>返回的文件名即上传后的文件名</returns> 
        public string SaveFile(HtmlInputFile hifile, string strAbsolutePath)
        {
            string strOldFilePath = "", strExtension = "", strNewFileName = "";

            //如果上传文件的文件名不为空 
            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名 
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //文件上传后的命名 
                strNewFileName = GetUniqueString("Guid") + strExtension;
                //如果路径末尾为\符号，则直接上传文件 
                if (strAbsolutePath.LastIndexOf("\\") == strAbsolutePath.Length)
                {
                    hifile.PostedFile.SaveAs(strAbsolutePath + strNewFileName);
                }
                else
                {
                    hifile.PostedFile.SaveAs(strAbsolutePath + "\\" + strNewFileName);
                }
            }
            return strNewFileName;
        }
        #endregion

        #region 重新上传文件，删除原有文件CoverFile
        /// <summary> 
        /// 重新上传文件，删除原有文件 
        /// </summary> 
        /// <param name="ffFile">HtmlInputFile控件</param> 
        /// <param name="strAbsolutePath">绝对路径.如:Server.MapPath(@"Image/upload")与Server.MapPath(@"Image/upload/")均可,用\符号亦可</param> 
        /// <param name="strOldFileName">旧文件名</param> 
        public void CoverFile(HtmlInputFile ffFile, string strAbsolutePath, string strOldFileName)
        {
            //获得新文件名 
            string strNewFileName = GetUniqueString();

            if (ffFile.PostedFile.FileName != string.Empty)
            {
                //旧图片不为空时先删除旧图片 
                if (strOldFileName != string.Empty)
                {
                    DeleteFile(strAbsolutePath, strOldFileName);
                }
                SaveFile(ffFile, strAbsolutePath);
            }
        }
        #endregion

        #region
        public static void initJavascript()
        {
            HttpContext.Current.Response.Write(" <script language=JavaScript type=text/javascript>");
            HttpContext.Current.Response.Write("var t_id = setInterval(animate,20);");
            HttpContext.Current.Response.Write("var pos=0;var dir=2;var len=0;");
            HttpContext.Current.Response.Write("function animate(){");
            HttpContext.Current.Response.Write("var elem = document.getElementById('progress');");
            HttpContext.Current.Response.Write("if(elem != null) {");
            HttpContext.Current.Response.Write("if (pos==0) len += dir;");
            HttpContext.Current.Response.Write("if (len>32 || pos>79) pos += dir;");
            HttpContext.Current.Response.Write("if (pos>79) len -= dir;");
            HttpContext.Current.Response.Write(" if (pos>79 && len==0) pos=0;");
            HttpContext.Current.Response.Write("elem.style.left = pos;");
            HttpContext.Current.Response.Write("elem.style.width = len;");
            HttpContext.Current.Response.Write("}}");
            HttpContext.Current.Response.Write("function remove_loading() {");
            HttpContext.Current.Response.Write(" this.clearInterval(t_id);");
            HttpContext.Current.Response.Write("var targelem = document.getElementById('loader_container');");
            HttpContext.Current.Response.Write("targelem.style.display='none';");
            HttpContext.Current.Response.Write("targelem.style.visibility='hidden';");
            HttpContext.Current.Response.Write("}");
            HttpContext.Current.Response.Write("</script>");
            HttpContext.Current.Response.Write("<style>");
            HttpContext.Current.Response.Write("#loader_container {text-align:center; position:absolute; top:40%; width:100%; left: 0;}");
            HttpContext.Current.Response.Write("#loader {font-family:Tahoma, Helvetica, sans; font-size:11.5px; color:#000000; background-color:#FFFFFF; padding:10px 0 16px 0; margin:0 auto; display:block; width:130px; border:1px solid #5a667b; text-align:left; z-index:2;}");
            HttpContext.Current.Response.Write("#progress {height:5px; font-size:1px; width:1px; position:relative; top:1px; left:0px; background-color:#8894a8;}");
            HttpContext.Current.Response.Write("#loader_bg {background-color:#e4e7eb; position:relative; top:8px; left:8px; height:7px; width:113px; font-size:1px;}");
            HttpContext.Current.Response.Write("</style>");
            HttpContext.Current.Response.Write("<div id=loader_container>");
            HttpContext.Current.Response.Write("<div id=loader>");
            HttpContext.Current.Response.Write("<div align=center>页面正在加载中 ...</div>");
            HttpContext.Current.Response.Write("<div id=loader_bg><div id=progress> </div></div>");
            HttpContext.Current.Response.Write("</div></div>");
            HttpContext.Current.Response.Flush();
        }
        #endregion

        #region 判断文件上传是否为指定类型(如有多个类型用/隔开。如："JPG/PNG")
        /// <summary>
        /// 判断文件上传是否为指定类型(如有多个类型用/隔开。如："JPG/PNG")
        /// 作者：卢亚东
        /// 时间：2011-7-15
        /// </summary>
        /// <param name="hifile">html上传控件的名字</param>
        /// <param name="typename">要限制的上传的文件类型（多个用/隔开，如："JPG/PNG"）</param>
        /// <returns></returns>
        public static bool CheckFileType(HtmlInputFile hifile, string typename)
        {
            return CheckFileType(hifile.PostedFile.FileName, typename);
        }
        #endregion

        /// <summary>
        /// 判断文件上传是否为指定类型(如有多个类型用/隔开。如："JPG/PNG")
        /// 作者：卢亚东
        /// 时间：2011-9-19
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="typename">要限制的上传的文件类型（多个用/隔开，如："JPG/PNG"）</param>
        /// <returns></returns>
        public static bool CheckFileType(string fileName, string typename)
        {
            string strOldFilePath = "";
            string strExtension = "";

            //允许上传的扩展名，可以改成从配置文件中读出 
            string[] arrExtension = typename.Split('/');

            if (fileName != string.Empty)
            {
                strOldFilePath = fileName;
                //取得上传文件的扩展名 
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".") + 1).ToUpper();
                //判断该扩展名是否合法 
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.Equals(arrExtension[i]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        #region 判断指定路径文件夹是否存在
        /// <summary>
        /// 检查指定文件夹是否存在
        /// 作者：卢亚东
        /// 时间：2011-7-18
        /// </summary>
        /// <param name="Folderpath">此路径为绝对路径，可通过Server.MapPath("~/upimg/hufu")获取</param>
        /// <returns></returns>
        public static bool CheckFolderExists(string Folderpath)
        {
            if (Directory.Exists(Folderpath) == false)
            {
                return false;
            }
            else
            {
                return true;//该文件夹已存在
            }
        }
        #endregion
        /// <summary>
        /// 创建指定路径文件夹
        /// 作者：卢亚东
        /// 时间：2011-7-18
        /// </summary>
        /// <param name="Folderpath">此路径为绝对路径，可通过Server.MapPath("~/upimg/hufu")获取</param>
        /// <returns></returns>
        public static bool CreateFolder(string Folderpath)
        {
            try
            {
                Directory.CreateDirectory(Folderpath);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 根据所要上传的文件所要放的文件夹产生当天的日期目录
        /// </summary>
        /// <param name="path">所要上传的文件的目录</param>
        /// <returns></returns>
        public static string GetDateFolderPath(string path)
        {
            DateTime time = DateTime.Now;
            return path + "/" + time.Year + time.Month + "/";
        }
        /// <summary>
        /// 保存上传文件，返回一个GUID产生的表示的名字的文件名称
        /// 作者：卢亚东
        /// 时间：2011-9-19
        /// </summary>
        /// <param name="hifile">服务器上传控件名称</param>
        /// <param name="path">绝对路径.如:Server.MapPath(@"Image/upload")与Server.MapPath(@"Image/upload/")均可,用\符号亦可</param>
        /// <returns></returns>
        public static string SaveFileMakeGUID(System.Web.UI.WebControls.FileUpload hifile, string path)
        {
            string strOldFilePath = "", strExtension = "", strNewFileName = "";

            //如果上传文件的文件名不为空 
            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名 
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //文件上传后的命名 （GUID）
                strNewFileName = Guid.NewGuid().ToString().Replace("-","") + strExtension;
                
                //如果路径末尾为\符号，则直接上传文件 
                if (path.LastIndexOf("\\") == path.Length)
                {
                    hifile.PostedFile.SaveAs(path + strNewFileName);
                }
                else
                {
                    hifile.PostedFile.SaveAs(path + "\\" + strNewFileName);
                }
            }
            return strNewFileName;
        }
        /// <summary>
        /// 获取文件的后缀名（带有.符号）
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public static string GetExtention(string filename)
        {
            return filename.Substring(filename.LastIndexOf("."));
        }
        /// <summary>
        /// 保存上传文件，返回一个GUID产生的表示的名字的文件名称
        /// 作者：卢亚东
        /// 时间：2011-7-18
        /// </summary>
        /// <param name="hifile">上传控件名称</param>
        /// <param name="path">绝对路径.如:Server.MapPath(@"Image/upload")与Server.MapPath(@"Image/upload/")均可,用\符号亦可</param>
        /// <returns></returns>
        public static string SaveFileMakeGUID(HtmlInputFile hifile, string path)
        {
            string strOldFilePath = "", strExtension = "", strNewFileName = "";

            //如果上传文件的文件名不为空 
            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名 
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //文件上传后的命名 （GUID）
                strNewFileName = Guid.NewGuid().ToString() + strExtension;

                //如果路径末尾为\符号，则直接上传文件 
                if (path.LastIndexOf("\\") == path.Length)
                {
                    hifile.PostedFile.SaveAs(path + strNewFileName);
                }
                else
                {
                    hifile.PostedFile.SaveAs(path + "\\" + strNewFileName);
                }
            }
            return strNewFileName;
        }
        /// <summary>
        /// 产生GUID
        /// </summary>
        /// <returns></returns>
        public static string MakeGUID()
        {
            return Guid.NewGuid().ToString();
        }
        /// <summary>
        /// 检查上传文件的大小
        /// 作者：卢亚东
        /// 时间：2011-7-18
        /// </summary>
        /// <param name="hifile">html上传控件名称</param>
        /// <param name="size">上传文件的限制大小（以M为单位，如：上传限制大小为一兆,则size=1）</param>
        /// <returns></returns>
        public static bool CheckFileSize(HtmlInputFile hifile, int size)
        {
            return CheckFileSize(hifile.PostedFile.ContentLength, size);
        }
        /// <summary>
        /// 检查上传文件的大小
        /// 作者：卢亚东
        /// 时间：2011-7-18
        /// </summary>
        /// <param name="hifile">上传文件的大小(以K为单位)</param>
        /// <param name="size">上传文件的限制大小（以M为单位，如：上传限制大小为一兆,则size=1）</param>
        /// <returns></returns>
        public static bool CheckFileSize(int contentLength, int size)
        {
            if (contentLength > size * 1024 * 1024)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 检查上传图片的宽度和高度是否符合要求
        /// 作者：卢亚东
        /// 时间：2011-7-19
        /// </summary>
        /// <param name="hifile">上传控件</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static string CheckFileWidthAndHieght(HtmlInputFile hifile, int width, int height)
        {
            return CheckFileWidthAndHieght(hifile.PostedFile.InputStream, width, height);
        }
        /// <summary>
        /// 检查上传图片的宽度和高度是否符合要求
        /// 作者：卢亚东
        /// 时间：2011-9-19
        /// </summary>
        /// <param name="hifile">文件流</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static string CheckFileWidthAndHieght(System.IO.Stream inputStream, int width, int height)
        {
            System.Drawing.Image img = System.Drawing.Image.FromStream(inputStream);
            if (img.Height > height)
                return "您上传的图片高度不符合要求";
            else if (img.Width > width)
                return "您上传的图片宽度不符合要求";
            return "";
        }
        /// <summary>
        /// 检查上传图片的宽度和高度是否符合要求(返回信息比较详细，如果高度超过，返回值都包含H,宽度超过，返回值都包含W)
        /// 作者：卢亚东
        /// 时间：2011-9-21
        /// </summary>
        /// <param name="hifile">文件流</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static string CheckFileWidthAndHeightAdvanced(System.IO.Stream inputStream, int Width, int Height)
        {
            System.Drawing.Image img = System.Drawing.Image.FromStream(inputStream);
            if (img.Width > Width)
            {
                if (img.Height > Height)
                {
                    return "MWH";//M:more 更多，W:width 宽度，H:height 高度，宽度和高度都超过
                }
                else
                {
                    return "MW";//M:more 更多，W:width 宽度 宽度超过，高度没有超过
                }
            }
            else
            {
                if (img.Height > Height)
                {
                    return "MH"; //M:more 更多 H:height 高度 宽度没有超过，高度超过
                }
                else
                {
                    return "";//宽度，高度都没有超过指定宽度
                }
            }
        }
        /// <summary>
        /// 上传文件,并返回一个文件新名称(GUID名称)
        /// 作者:卢亚东
        /// 时间：2011-7-18
        /// </summary>
        /// <param name="hifile">(必填)上传控件名称</param>
        /// <param name="savepath">(必填)要上传的路径，可通过Server.MapPath("~/upimg/hufu")获取</param>
        /// <param name="typename">>(可空)要限制的上传的文件类型（多个用/隔开，如："JPG/PNG",默认类型为：GIF/JPG/JPEG/BMP/PNG）</param>
        /// <param name="size">(必填)上传文件的限制大小(以M为单位，如：上传限制大小为一兆,则size=1)</param>
        /// <returns></returns>
        public static string UploadFile(HtmlInputFile hifile, string savepath, string typename, int size)
        {
            if (string.IsNullOrEmpty(hifile.PostedFile.FileName))
            {
                return "错误：上传文件不能为空";
            }
            if (string.IsNullOrEmpty(typename))
            {
                typename = "GIF/JPG/JPEG/BMP/PNG";//设置默认上传文件的类型
            }
            if (CheckFileType(hifile, typename))//检查文件类型是否合法
            {
                if (CheckFileSize(hifile, size))//检查上传文件大小
                {

                    string truepath = UpFile.GetDateFolderPath(savepath);//获取要保存的文件的真实路径
                    if (!CheckFolderExists(truepath))//验证该真实路径是否存在
                    {
                        if (!CreateFolder(truepath))//创建该真实路径
                        {
                            return "错误：创建文件夹失败！请重试";
                        }
                    }
                    return SaveFileMakeGUID(hifile, truepath);//保存文件，并产生一个GUID名称
                }
                return "错误：上传文件大小不能超过" + size + "M";
            }
            return "错误：上传文件类型不正确，必须为：" + typename + "格式的文件！";
        }
        /// <summary>
        /// 上传文件,并返回一个文件新名称(GUID名称)
        /// 作者:卢亚东
        /// 时间：2011-7-18
        /// </summary>
        /// <param name="hifile">(必填)上传控件名称</param>
        /// <param name="savepath">(必填)要上传的路径，可通过Server.MapPath("~/upimg/hufu")获取</param>
        /// <param name="typename">>(可空)要限制的上传的文件类型（多个用/隔开，如："JPG/PNG",默认类型为：GIF/JPG/JPEG/BMP/PNG）</param>
        /// <param name="size">(必填)上传文件的限制大小(以M为单位，如：上传限制大小为一兆,则size=1)</param>
        /// <returns></returns>
        public static string UploadFile(System.Web.UI.WebControls.FileUpload hifile, string savepath, string typename, int size)
        {
            return UploadFile(hifile, savepath, typename, size, 900);
        }
        /// <summary>
        /// 上传文件,并返回一个文件新名称(GUID名称)
        /// 作者:卢亚东
        /// 时间：2011-9-21
        /// </summary>
        /// <param name="hifile">(必填)上传控件名称</param>
        /// <param name="savepath">(必填)要上传的路径，可通过Server.MapPath("~/upimg/hufu")获取</param>
        /// <param name="typename">(可空)要限制的上传的文件类型（多个用/隔开，如："JPG/PNG",默认类型为：GIF/JPG/JPEG/BMP/PNG）</param>
        /// <param name="size">(必填)上传文件的限制大小(以M为单位，如：上传限制大小为一兆,则size=1)</param>
        /// <param name="maxwidth">最大宽度</param>
        /// <returns></returns>
        public static string UploadFile(System.Web.UI.WebControls.FileUpload hifile, string savepath, string typename, int size, int maxwidth)
        {
            if (string.IsNullOrEmpty(hifile.PostedFile.FileName))
            {
                return "错误：上传文件不能为空";
            }
            if (string.IsNullOrEmpty(typename))
            {
                typename = "GIF/JPG/JPEG/BMP/PNG";//设置默认上传文件的类型
            }
            if (CheckFileType(hifile.PostedFile.FileName, typename))//检查文件类型是否合法
            {
                if (CheckFileSize(hifile.PostedFile.ContentLength, size))//检查上传文件大小
                {

                    string truepath = UpFile.GetDateFolderPath(savepath);//获取要保存的文件的真实路径
                    string NewFileName = string.Empty;
                    if (!CheckFolderExists(truepath))//验证该真实路径是否存在
                    {
                        if (!CreateFolder(truepath))//创建该真实路径
                        {
                            return "错误：创建文件夹失败！请重试";
                        }
                    }
                    if (CheckFileWidthAndHieght(hifile.PostedFile.InputStream, 900, 1200).Length > 0)//判断上传图片的宽度和高度
                    {
                        NewFileName = Guid.NewGuid().ToString().Replace("-","") + hifile.PostedFile.FileName.Substring(hifile.PostedFile.FileName.LastIndexOf("."));
                        //如果宽度超过900，等比例压缩图片保存
                        MakeThumbnail2(hifile.PostedFile.InputStream, truepath + NewFileName, maxwidth, 100, "W");
                    }
                    else
                    {
                        NewFileName = SaveFileMakeGUID(hifile, truepath);//保存文件，并产生一个GUID名称
                    }
                    return NewFileName;
                }
                return "错误：上传文件大小不能超过" + size + "M";
            }
            return "错误：上传文件类型不正确，必须为：" + typename + "格式的文件！";
        }
        /// <summary>
        /// 上传文档类文件,并返回一个文件新名称(GUID名称)
        /// 作者:卢亚东
        /// 时间:2012-3-6
        /// </summary>
        /// <param name="hifile">(必填)上传控件名称</param>
        /// <param name="savepath">(必填)要上传的路径，可通过Server.MapPath("~/upimg/hufu")获取</param>
        /// <param name="typename">(可空)要限制的上传的文件类型（多个用/隔开，如："DOC/PDF",默认类型为：DOC/PDF/DOCX）</param>
        /// <param name="size">(必填)上传文件的限制大小(以M为单位，如：上传限制大小为一兆,则size=1)</param>
        /// <returns>如成功则返回保存额文件名，失败则返回失败信息</returns>
        public static string UpDocFile(System.Web.UI.WebControls.FileUpload hifile, string savepath, string typename, int size)
        {
            if (string.IsNullOrEmpty(hifile.PostedFile.FileName))
            {
                return "错误：上传文件不能为空";
            }
            if (string.IsNullOrEmpty(typename))
            {
                typename = "DOC/PDF/DOCX";//设置默认上传文件的类型
            }
            if (CheckFileType(hifile.PostedFile.FileName, typename))//检查文件类型是否合法
            {
                if (CheckFileSize(hifile.PostedFile.ContentLength, size))//检查上传文件大小
                {

                    string truepath = UpFile.GetDateFolderPath(savepath);//获取要保存的文件的真实路径
                    string NewFileName = string.Empty;
                    if (!CheckFolderExists(truepath))//验证该真实路径是否存在
                    {
                        if (!CreateFolder(truepath))//创建该真实路径
                        {
                            return "错误：创建文件夹失败！请重试";
                        }
                    }
                    else
                    {
                        NewFileName = SaveFileMakeGUID(hifile, truepath);//保存文件，并产生一个GUID名称
                    }
                    return NewFileName;
                }
                return "错误：上传文件大小不能超过" + size + "M";
            }
            return "错误：上传文件类型不正确，必须为：" + typename + "格式的文件！";
        }
        /// <summary>
        /// 生成缩略图
        /// 作者：卢亚东
        /// 时间：2011-8-3
        /// </summary>
        /// <param name="originalImagePath">原始路径（绝对路径包含上传文件的名称）</param>
        /// <param name="thumbnailPath">保存的缩率图的路径（绝对路径包含上传文件的名称）</param>
        /// <param name="width">缩略图的宽度</param>
        /// <param name="height">缩略图的高度</param>
        /// <param name="mode">状态（为Cut时，为不变形的压缩，W 指定宽度，高按比例，H 指定高，宽按比例，WH 指定宽高缩放(可能变形)）</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                               
                    break;
                case "W"://指定宽，高按比例                                   
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例  
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                               
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片        
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板        
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法        
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度        
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充        
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分        
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            try
            {            //以jpg格式保存缩略图            
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 生成缩略图
        /// 作者：卢亚东
        /// 时间：2011-8-3
        /// </summary>
        /// <param name="originalImagePath">上传控件(html)的名称</param>
        /// <param name="thumbnailPath">保存的缩率图的路径（绝对路径包含上传文件的名称）</param>
        /// <param name="width">缩略图的宽度</param>
        /// <param name="height">缩略图的高度</param>
        /// <param name="mode">状态（为Cut时，为不变形的压缩，W 指定宽度，高按比例，H 指定高，宽按比例，WH 指定宽高缩放(可能变形)）</param>
        public static void MakeThumbnail2(HtmlInputFile hifile, string thumbnailPath, int width, int height, string mode)
        {
            MakeThumbnail2(hifile.PostedFile.InputStream, thumbnailPath, width, height, mode);
        }
        /// <summary>
        /// 生成缩略图
        /// 作者：卢亚东
        /// 时间：2011-12-26
        /// </summary>
        /// <param name="originalImage">图片</param>
        /// <param name="thumbnailPath">保存的缩率图的路径（绝对路径包含上传文件的名称）</param>
        /// <param name="width">缩略图的宽度</param>
        /// <param name="height">缩略图的高度</param>
        /// <param name="mode">状态（为Cut时，为不变形的压缩，W 指定宽度，高按比例，H 指定高，宽按比例，WH 指定宽高缩放(可能变形)）</param>
        public static void MakeThumbnail2(Image originalImage, string thumbnailPath, int width, int height, string mode)
        {
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                               
                    break;
                case "W"://指定宽，高按比例                                   
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例  
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                               
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片        
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板        
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法        
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度        
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充        
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分        
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            try
            {            //以jpg格式保存缩略图            
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 生成缩略图
        /// 作者：卢亚东
        /// 时间：2011-8-11
        /// </summary>
        /// <param name="inputstream">文件流</param>
        /// <param name="thumbnailPath">保存的缩率图的路径（绝对路径包含上传文件的名称）</param>
        /// <param name="width">缩略图的宽度</param>
        /// <param name="height">缩略图的高度</param>
        /// <param name="mode">状态（为Cut时，为不变形的压缩，W 指定宽度，高按比例，H 指定高，宽按比例，WH 指定宽高缩放(可能变形)）</param>
        public static void MakeThumbnail2(Stream inputstream, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(inputstream);
            MakeThumbnail2(originalImage, thumbnailPath, width, height, mode);
        }
        /// <summary>
        /// 剪裁图像
        /// </summary>
        /// <param name="Img"></param>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        /// <param name="X"></param>
        /// <param name="Y"></param>
        /// <returns></returns>
        public static byte[] Crop(string Img, int Width, int Height, int X, int Y, string newpath)
        {
            try
            {
                using (var OriginalImage = new Bitmap(Img))
                {
                    using (var bmp = new Bitmap(Width, Height, OriginalImage.PixelFormat))
                    {
                        bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                        using (Graphics Graphic = Graphics.FromImage(bmp))
                        {
                            Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                            Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, Width, Height), X, Y, Width, Height,
                                              GraphicsUnit.Pixel);
                            bmp.Save(newpath, OriginalImage.RawFormat);
                            var ms = new MemoryStream();
                            bmp.Save(ms, OriginalImage.RawFormat);

                            return ms.GetBuffer();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
        }


        public static byte[] CropImage(string originaImgPath, int width, int height, int x, int y, string newpath)
        {
            byte[] CropImage = Crop(originaImgPath, width, height, x, y, newpath);
            return CropImage;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
